const path = require('path')
    , express = require('express')
    , app = express()
    , http = require('http')
    , server = http.createServer(app)
    , port = 3000
    , engine = require('ejs-locals')
    , config = require("./app/config/config")
    //On récupère les schéma de la bdd
    , db = require("./app/config/database")(config)
    , dao = require('./app/config/dao')
    ;
 
/** Configuration */
app.configure(function() {

  this.engine('ejs', engine);
  this.set('views', path.join(__dirname, '/app/views'));
  this.set('view engine', 'ejs');

  //Permet de référerencer le dossiers des ressources statiques
  this.use(express.static(path.join(__dirname, '/public')));

  this.use(express.logger('dev'));  /* 'default', 'short', 'tiny', 'dev' */

  // Autoriser à parser les données du formulaire
  this.use(express.bodyParser());

  // Autorise à parser les cookies depuis le header de la requete
  this.use(express.cookieParser());

  // Session management
  this.use(express.session({
      // Private clé
      "secret": "myappli",
      // Internal session data storage engine, this is the default engine embedded with connect.
      // Much more can be found as external modules (Redis, Mongo, Mysql, file...). look at "npm search connect session store"
      "store":  new express.session.MemoryStore({ reapInterval: 60000 * 10 })
  }));
});


/** Routes */
app.get('/',function(req, res, next){
    console.log("On get  / ");

    //if (req.session.username) {
    var scripts = ['js/utils.js','js/views/login.js','js/models/user.js', 'js/routes/route.js'];
    var styles = ['css/reset.css','css/bootstrap.min.css','css/bootstrap-responsive.min.css','css/styles.css'];
    res.render('layout',{"scripts" : scripts, "styles" : styles});
    /*} else {
      //Sinon on redirige vers la page de login
      res.redirect("/login"userDAO);
    }*/
});

app.get('/user', function(req, res)
{
    console.log("On get /user");
    dao.userDAO.findAll(req, res, db);
});

app.post('/user',function(req, res, next)
{
   console.log("On post /user");
   dao.userDAO.addUser(req, res, db);
});

app.post('/login',function(req,res, next)
{
    console.log("On post /login");
    dao.userDAO.checkLogin(req, res, db);
});


/** Start server */
if (!module.parent) {
  server.listen(port, function () {
    console.log('Listening', this.address());
   })
}

var sockets = require('socket.io').listen(server);

